package com.quickstart.common;

import com.quickstart.common.date.DateTimeUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author:wesley
 */

@Controller
@RequestMapping(value = "/common")
public class CommonController {

    private final String BASEPATH = "D:/upload";
    private final String UEIMAGEPATH = "/ue/image";
    private final String UEVIDEOPATH = "/ue/video";


    @RequestMapping(value = "/upload/image")
    @ResponseBody
    public Map<String,Object> uploadImage(MultipartHttpServletRequest request) {
        File floder = new File(BASEPATH+UEIMAGEPATH);
        Map<String,Object> map = uplaodFile(floder, request,1);
        return map;
    }


    @RequestMapping(value = "/upload/video")
    @ResponseBody
    public Map<String,Object> uploadVideo(MultipartHttpServletRequest request) {
        File floder = new File(BASEPATH+UEVIDEOPATH);
        Map<String,Object> map = uplaodFile(floder, request,2);
        return map;
    }



    private Map<String,Object> uplaodFile(File floder, MultipartHttpServletRequest request,int type){
        Map<String,Object> map = new HashMap<>();
        if (!floder.exists()){
            floder.mkdirs();
        }

        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()){
            String fileName = fileNames.next();
            MultipartFile file = request.getFile(fileName);
            String fileStuffix = getFileNameStuffix(file.getOriginalFilename());

            String newFileName = DateTimeUtils.formatDate(new Date(),
                    "yyyyMMddHHmmss")+fileStuffix;

            File outFile = new File(floder.getPath()+ File.separator+newFileName );

            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(),outFile);
                if(type == 1){
                    map.put("url", "/upload/"+UEIMAGEPATH+File.separator+newFileName);
                } else {
                    map.put("url", "/upload/"+UEVIDEOPATH+File.separator+newFileName);
                }

                map.put("state", "SUCCESS");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }


    /**
     * 返回文件后缀名
     *
     * @param fileName  123456.mp4
     * @return .mp4
     */
    private String getFileNameStuffix(String fileName){
        int lastIndex = fileName.lastIndexOf(".");
        return fileName.substring(lastIndex);
    }


}
